package com.copa.controller;

import com.copa.entity.AjaxResult;
import com.copa.entity.IHttpMessage;
import com.copa.service.GroupService;
import com.copa.service.PrivateService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;

import static com.copa.constant.MessageType.PIC_MESSAGE;
import static com.copa.utils.JsonUtil.dealMsg;


/**
 * @Description: 消息接收器
 * @Date: 2022/2/16 10:09
 * @Version: 1.0
 */
@RestController
@RequestMapping("/debug")
public class MessageController {

    private static final Logger LOG = LoggerFactory.getLogger(MessageController.class);

    @Autowired
    private PrivateService privateService;

    @Autowired
    private GroupService groupService;

    /**
     * 同下
     * @param iHttpMessage
     * @return
     */
    @GetMapping
    public AjaxResult messageGet(@RequestBody IHttpMessage iHttpMessage) {
        if(null!=iHttpMessage) {
            LOG.info(iHttpMessage.toString());
        }
        return AjaxResult.success();
    }

    /**
     * 可爱猫发过来的是json格式的数据，使用@RequestBody 接受
     * @param json
     * @return
     */
    @PostMapping
    public AjaxResult messagePost(@RequestBody String json) throws IOException {
        //System.out.println(json);
        IHttpMessage iHttpMessage = dealMsg(json);
        if(null!=iHttpMessage) {
            //LOG.info(iHttpMessage.toString());
            // 接收知乎公众号的图片并发送到群
            if (("gh_4132cd5238e8").equals(iHttpMessage.getFrom_wxid())
                && PIC_MESSAGE == iHttpMessage.getType()) {
                groupService.sendDailyNewsMessage(iHttpMessage);
                return AjaxResult.success();
            }
            // 公众号发来的不回复
            if (iHttpMessage.getFrom_wxid().startsWith("gh_")) {
                return AjaxResult.success();
            }
            // 如果消息来源不同
            if(!iHttpMessage.getFinal_from_wxid().equalsIgnoreCase(iHttpMessage.getRobot_wxid())) {
                // 群聊
                if (("EventGroupMsg").equals(iHttpMessage.getEvent())) {
                    groupService.sendMessage(iHttpMessage);
                } else {
                    // 私聊
                    privateService.sendMessage(iHttpMessage);
                }
            }
            return AjaxResult.success();
        }
        else {
            LOG.info("------消息为空-----非法请求");
            return AjaxResult.error();
        }
    }


}
